package wang.xinqiu.mysqlcontrol

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import kotlinx.coroutines.launch
import wang.xinqiu.mysqlcontrol.data.ConnectionInfo
import wang.xinqiu.mysqlcontrol.data.MySQLManager
import wang.xinqiu.mysqlcontrol.data.PreferencesManager
import wang.xinqiu.mysqlcontrol.ui.DatabaseScreen
import wang.xinqiu.mysqlcontrol.ui.LoginScreen
import wang.xinqiu.mysqlcontrol.ui.QueryScreen
import wang.xinqiu.mysqlcontrol.ui.TableViewScreen
import wang.xinqiu.mysqlcontrol.ui.TableDesignScreen
import wang.xinqiu.mysqlcontrol.ui.TableInfoScreen
import wang.xinqiu.mysqlcontrol.ui.theme.MySQLControlTheme
import android.util.Log
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MySQLControlTheme {
                MySQLControlApp()
            }
        }
    }
}

@Composable
fun MySQLControlApp() {
    val context = LocalContext.current
    val preferencesManager = remember { PreferencesManager(context) }
    val mysqlManager = remember { MySQLManager() }
    val scope = rememberCoroutineScope()
    
    var currentScreen by remember { mutableStateOf<Screen>(Screen.Login) }
    var connectionInfo by remember { mutableStateOf<ConnectionInfo?>(null) }
    var selectedDatabase by remember { mutableStateOf<String?>(null) }
    var selectedTable by remember { mutableStateOf<String?>(null) }
    var isEditingTable by remember { mutableStateOf(false) }
    var isCheckingSession by remember { mutableStateOf(true) }

    // 会话过期处理函数
    val handleSessionExpired = {
        scope.launch  {
            mysqlManager.disconnect()
        }
        preferencesManager.clearLastConnection()
        connectionInfo = null
        selectedDatabase = null
        selectedTable = null
        currentScreen = Screen.Login
    }

    // 检查上次会话
    LaunchedEffect(Unit) {
        val lastConnection = preferencesManager.getLastConnection()
        if (lastConnection != null) {
            val result = mysqlManager.connect(lastConnection)
            if (result.isSuccess) {
                connectionInfo = lastConnection
                currentScreen = Screen.DatabaseList
            } else {
                preferencesManager.clearLastConnection()
            }
        }
        isCheckingSession = false
    }

    if (isCheckingSession) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            CircularProgressIndicator()
        }
        return
    }

    Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
        when (currentScreen) {
            Screen.Login -> {
                LoginScreen(
                    modifier = Modifier.padding(innerPadding),
                    mysqlManager = mysqlManager,  // 传递共享的实例
                    onConnect = { connInfo ->
                        Log.d("MainActivity", "收到连接成功回调，准备跳转到数据库列表")
                        connectionInfo = connInfo
                        preferencesManager.saveLastConnection(connInfo)
                        currentScreen = Screen.DatabaseList
                        Log.d("MainActivity", "已切换到数据库列表界面")
                    }
                )
            }
            Screen.DatabaseList -> {
                connectionInfo?.let { connInfo ->
                    DatabaseScreen(
                        connectionInfo = connInfo,
                        mysqlManager = mysqlManager,  // 传递共享的实例
                        onBack = { 
                            scope.launch {
                                mysqlManager.disconnect()
                            }
                            preferencesManager.clearLastConnection()
                            currentScreen = Screen.Login 
                        },
                        onSessionExpired = handleSessionExpired,
                        onDatabaseSelected = { database ->
                            selectedDatabase = database
                            currentScreen = Screen.Query
                        },
                        onTableViewSelected = { database, table ->
                            selectedDatabase = database
                            selectedTable = table
                            currentScreen = Screen.TableView
                        },
                        onTableDesignSelected = { database, table, isEdit ->
                            selectedDatabase = database
                            selectedTable = table
                            isEditingTable = isEdit
                            currentScreen = Screen.TableDesign
                        },
                        onTableInfoSelected = { database, table ->
                            selectedDatabase = database
                            selectedTable = table
                            currentScreen = Screen.TableInfo
                        }
                    )
                }
            }
            Screen.Query -> {
                connectionInfo?.let { connInfo ->
                    selectedDatabase?.let { database ->
                        QueryScreen(
                            connectionInfo = connInfo,
                            databaseName = database,
                            mysqlManager = mysqlManager,  // 传递共享的实例
                            onBack = { currentScreen = Screen.DatabaseList },
                            onSessionExpired = handleSessionExpired
                        )
                    }
                }
            }
            Screen.TableView -> {
                connectionInfo?.let { connInfo ->
                    selectedDatabase?.let { database ->
                        selectedTable?.let { table ->
                            TableViewScreen(
                                connectionInfo = connInfo,
                                databaseName = database,
                                tableName = table,
                                mysqlManager = mysqlManager,  // 传递共享的实例
                                onBack = { currentScreen = Screen.DatabaseList },
                                onSessionExpired = handleSessionExpired
                            )
                        }
                    }
                }
            }
            Screen.TableDesign -> {
                connectionInfo?.let { connInfo ->
                    selectedDatabase?.let { database ->
                        TableDesignScreen(
                            databaseName = database,
                            tableName = if (isEditingTable) selectedTable else null,
                            mysqlManager = mysqlManager,
                            onBack = { currentScreen = Screen.DatabaseList },
                            onSessionExpired = handleSessionExpired
                        )
                    }
                }
            }
            Screen.TableInfo -> {
                connectionInfo?.let { connInfo ->
                    selectedDatabase?.let { database ->
                        selectedTable?.let { table ->
                            TableInfoScreen(
                                databaseName = database,
                                tableName = table,
                                mysqlManager = mysqlManager,
                                onBack = { currentScreen = Screen.DatabaseList },
                                onSessionExpired = handleSessionExpired
                            )
                        }
                    }
                }
            }
        }
    }
}

sealed class Screen {
    object Login : Screen()
    object DatabaseList : Screen()
    object Query : Screen()
    object TableView : Screen()
    object TableDesign : Screen()
    object TableInfo : Screen()
}
